# -*- coding: utf-8 -*-

from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required

import urllib
from .saltapi import salt
from .models import Minion, Server, ProcRunning, SysProc
from saltops.forms import PaginationForm

def query(req):
    form = PaginationForm(req.GET)
    if not form.is_valid():
        pass
    params = form.getPaginationParams()
    limit   = params['limit']
    offset  = params['offset']
    sort    = params['sort']
    order   = params['order']

    sysprocs = SysProc.objects.all()
    result = {'rows': [], 'total': sysprocs.count()}
    sysprocs = sysprocs[offset: offset + limit]
    result['rows'] = [sysproc.parse() for sysproc in sysprocs]
    return JsonResponse(result)

def create(req):
    pass

def update(req):
    pass

def delete(req):
    pass

def mark(req):
    '''
    将进程标记为系统进程
    '''
    result = {
        'code': 1,
        'msg': 'success'
    }
    psStr = req.POST['psStr']
    sysPorc = {
        'name': '',
        'ps_str': psStr,
        'desc': ''
    }
    try:
        SysProc.objects.create(**sysPorc)
    except Exception, e:
        result['code'] = -1
        result['msg'] = '%s' % e
    return JsonResponse(result)

def inlist(req):
    sysProcs = SysProc.objects.all()
    result = [sysProc.parse()['psStr'] for sysProc in sysProcs]
    return JsonResponse(result, safe = False)